package com.lc.zpyh.ui.activity.supermarket;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.lc.zpyh.R;
import com.lc.zpyh.adapter.BusinessAdapter;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.request.AddCartApi;
import com.lc.zpyh.http.request.CondimentsQueryApi;
import com.lc.zpyh.http.request.DeleteByIdsApi;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.request.SelectByNamedApi;
import com.lc.zpyh.http.request.SelectMyCartApi;
import com.lc.zpyh.http.request.SelectToBeConfirmedApi;
import com.lc.zpyh.http.request.SetByCommodityIdApi;
import com.lc.zpyh.http.response.CondimentsQueryBean;
import com.lc.zpyh.http.response.SelectByNameBean;
import com.lc.zpyh.http.response.SelectMyCartBean;
import com.lc.zpyh.http.response.SelectToBeConfirmedBean;
import com.lc.zpyh.http.response.SetByCommodityIdBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.CourseUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.view.GoodsAttrDialog;
import com.lc.zpyh.view.ShoppingCartDialog;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BusinessSearchActivity extends AppActivity {
    @BindView(R.id.et_search)
    EditText etSearch;

    @BindView(R.id.rv_goods_searches)
    RecyclerView rvGoodsSearches;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_xiadan)
    TextView tvXiadan;
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    @BindView(R.id.rl_diancanbottom)
    RelativeLayout rlDiancanbottom;
    private String merchantid;
    private BusinessAdapter.OnAddCartrListener onAddCartrListener;
    private BaseQuickAdapter<SelectByNameBean.ListBean, BaseViewHolder> adapter;
    private List<SelectByNameBean.ListBean> dataBeanList=new ArrayList<>();
    List<SelectMyCartBean.ListBean.CartsBean> datacartList = new ArrayList<>();
    private String shopname;
    List<String> orderList = new ArrayList<>();
    private ShoppingCartDialog shoppingCartDialog;
    List<CondimentsQueryBean.ListBean> dataxiaoliaoList = new ArrayList<>();
    private GoodsAttrDialog goodsAttrDialog;
    private String searchname;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_businesssearch;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        merchantid = getIntent().getStringExtra("merchantid");
        shopname = getIntent().getStringExtra("shopname");
        searchname = getIntent().getStringExtra("searchname");
        etSearch.setText(searchname);
        selectByName();
        adapter = new BaseQuickAdapter<SelectByNameBean.ListBean, BaseViewHolder>(R.layout.item_search_child, dataBeanList) {



            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, SelectByNameBean.ListBean bean) {


                Glide.with(BusinessSearchActivity.this)
                        .load(IntentKey.CAR_IMAGE+bean.getImg()).apply(new RequestOptions().placeholder(R.mipmap.zhanweiicon01).error(R.mipmap.zhanweiicon01))
                        .into((ImageView)baseViewHolder.getView(R.id.img_dianpu));
                baseViewHolder.setText(R.id.goods,bean.getName());

                TextView tv_yuanjia=baseViewHolder.getView(R.id.tv_yuanjia);
                TextView tv_number=  baseViewHolder.getView(R.id.tv_number);
                FrameLayout fl_reduce=baseViewHolder.getView(R.id.fl_reduce);
                FrameLayout fl_add=baseViewHolder.getView(R.id.fl_add);
                RelativeLayout rl_top=baseViewHolder.getView(R.id.rl_top);
                if (bean.getPrePrice()==null){
                    baseViewHolder.setGone(R.id.tv_xianjia,true);
                    tv_yuanjia.getPaint().setFlags(0);
                }else {
                    baseViewHolder.setVisible(R.id.tv_xianjia,true);
                    baseViewHolder.setText(R.id.tv_xianjia,"￥"+ BigDecimalUtils.div(bean.getPrePrice()+"","100",2)+"");
                    tv_yuanjia.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG |Paint.ANTI_ALIAS_FLAG);;
                }
                baseViewHolder.setText(R.id.tv_yueshou,"月售"+bean.getSales()+"仅剩"+bean.getInventory()+"份");
                baseViewHolder.setText(R.id.tv_yuanjia,"￥"+ BigDecimalUtils.div(bean.getPrice()+"","100",2)+"");


              if (bean.getIs_sold_out()==0){
                  baseViewHolder.setGone(R.id.rl_status,true);
                  fl_reduce.setEnabled(true);
                  rl_top.setEnabled(true);
                  fl_add.setEnabled(true);
              }else {
                  baseViewHolder.setVisible(R.id.rl_status, true);
                  fl_reduce.setEnabled(false);
                  rl_top.setEnabled(false);
                  fl_add.setEnabled(false);
              }
            int count=0;
                int cartId=0;
              if (bean.getCartCount()!=null&&bean.getCartCount().size()>0) {
                  for (int i = 0; i < bean.getCartCount().size(); i++) {

                      count = count+bean.getCartCount().get(i).getCount();
                      if (bean.getCartCount().get(i).getCartId()!=null) {
                          cartId = bean.getCartCount().get(i).getCartId();
                      }
                  }
                  if (count == 0) {
                      baseViewHolder.setVisible(R.id.fl_reduce, false);
                      baseViewHolder.setVisible(R.id.tv_number, false);
                  } else {
                      baseViewHolder.setText(R.id.tv_number, count + "");
                      baseViewHolder.setVisible(R.id.fl_reduce, true);
                      baseViewHolder.setVisible(R.id.tv_number, true);
                  }

              } else {
                  count = 0;
                  baseViewHolder.setVisible(R.id.fl_reduce, false);
                  baseViewHolder.setVisible(R.id.tv_number, false);

              }


                baseViewHolder.getView(R.id.fl_add).setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                      double price;


                      if (   bean.getPrePrice()!=null){
                          price = Double.parseDouble(bean.getPrePrice()+"");
                      }else {
                          price = bean.getPrice();
                      }
//                      if (datacartList.size()>0) {
//                          Log.e("@@@", "onAddShoppingCart: " + useLoop(datacartList, bean.getId() + ""));
//                          if (useLoop(datacartList, bean.getId() + "")) {
//                              if (String.valueOf(count).equals("0")) {
//                                  deleteByIds(bean.getId() + "");
//                              } else
//                                  addShopCart(bean.getId() + "", count +"", "", price+"", "");
//                          }else {
                              isAttr(bean.getId()+"", 1 +"", "", BigDecimalUtils.mul(price+"","1",0), bean.getName(), "");
//                          }

//                      }else {
//                          isAttr(bean.getId()+"", count +"", "", price+"", bean.getName(), "condimentsId");
//                      }
                      if (onAddCartrListener != null) {
                          onAddCartrListener.onAddShoppingCart(bean.getId() + "", 1 + "", "", price + "", bean.getName(), "","","");
                      }
                  }
              });
                int finalCartId = cartId;
                baseViewHolder.getView(R.id.fl_reduce).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        double price;
                        int countcart= Integer.parseInt(tv_number.getText().toString())-1;
                        if (   bean.getPrePrice()!=null){
                            price = Double.parseDouble(bean.getPrePrice()+"");
                        }else {
                            price = bean.getPrice();
                        }
//                    count--;
                        if (bean.getCartCount()!=null&&bean.getCartCount().size()>1){
                            ToastUtils.show("不同规格商品需在购物车减购");
                        }else {
//                            if (countcart==0) {
//
//                                deleteByIds(finalCartId+"");
//                            } else {

                                addShopCart(bean.getId()+"", "-1", "", BigDecimalUtils.mul(price+"","1",0)+"", "");
//                            }
                        }

                    }
                });
                baseViewHolder.getView(R.id.rl_top).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        double price;
                        if (   bean.getPrePrice()!=null){
                            price = Double.parseDouble(bean.getPrePrice()+"");
                        }else {
                            price = bean.getPrice();
                        }
                        Log.e("@@@", "onClick: "+price);
                       startActivity(new Intent(BusinessSearchActivity.this,ShopDetailsActivity.class).putExtra("commodityId",bean.getId()+"").putExtra("merchantid",merchantid).putExtra("img",bean.getImg()).putExtra("shopname", shopname).putExtra("commodityname",bean.getName()).putExtra("price",price+""));
                    }
                });
            }
        };
        View emptyview = View.inflate(getContext(), R.layout.empty_emptylayout, null);

        adapter.setEmptyView(emptyview);
        rvGoodsSearches.setAdapter(adapter);

        selectMyCart();
    }



    private void selectMyCart() {
        EasyHttp.post(this)
                .api(new SelectMyCartApi().setUserid(SPUtil.get(this, IntentKey.USERID, "")).setPageNum("1").setPageSize("99").setMerchantid(merchantid).setSchoolid(SPUtil.get(this, IntentKey.ADDRESSID, ""))).request(new HttpCallback<SelectMyCartBean>(this) {

            @Override
            public void onSucceed(SelectMyCartBean data) {
                if (data.getCode() == 0) {
                    if (data.getList().size() > 0) {
                        tvXiadan.setVisibility(View.VISIBLE);
                        String totalNum = "0";
                        String totalPrice = "0";
                        for (int i = 0; i < data.getList().get(0).getCarts().size(); i++) {
                            if (data.getList().get(0).getCarts().get(i).getGgzzt()==null){
                                data.getList().get(0).getCarts().get(i).setGgzzt(0);
                            }
                            if (data.getList().get(0).getCarts().get(i).getSpzt()==0&&data.getList().get(0).getCarts().get(i).getGgzzt()==0) {
                                totalNum = BigDecimalUtils.add(totalNum, data.getList().get(0).getCarts().get(i).getCount() + "", 0);
                                totalPrice = BigDecimalUtils.add(totalPrice, BigDecimalUtils.mul(BigDecimalUtils.div(data.getList().get(0).getCarts().get(i).getPrice() + "", "100", 2), data.getList().get(0).getCarts().get(i).getCount() + "", 2), 2);
                            }else {

                            }
                        }

                        tvMoney.setText(totalPrice);
                        tvNum.setText("已选" + totalNum + "件");
                        datacartList.clear();
                        if (data.getList().size()>0) {
                            datacartList.addAll(data.getList().get(0).getCarts());
                        }
                        if (shoppingCartDialog != null) {
                            shoppingCartDialog.setDataList(datacartList);
                        }
                    } else {
                        tvXiadan.setVisibility(View.INVISIBLE);
                        tvMoney.setText("0.00");
                        tvNum.setText("已选" + "0" + "件");
                        datacartList.clear();
                        if (shoppingCartDialog != null) {
                            shoppingCartDialog.setDataList(datacartList);
                        }
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    private void selectByName() {

        EasyHttp.post(this)
                .api(new SelectByNamedApi().setUserId(SPUtil.get(this,IntentKey.USERID,"")).setMerchantid(merchantid).setName(etSearch.getText().toString().trim()).setPageNum("1").setPageSize("999")).request(new OnHttpListener<SelectByNameBean>() {

            @Override
            public void onSucceed(SelectByNameBean data) {
//
                if (data.getCode()==0){
                    dataBeanList.clear();
                    dataBeanList.addAll(data.getList());
                    adapter.setNewData(dataBeanList);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(Exception e) {


            }
        });
    }

    private void deleteByIds(String id) {
        EasyHttp.post(this)
                .api(new DeleteByIdsApi().setIds(id)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode() == 0) {
                    selectMyCart();
                  selectByName();
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void addShopCart(String id, String count, String specificationId, String price, String condimentsId) {


        EasyHttp.post(this)
                .api(new AddCartApi().setUserId(SPUtil.get(this, IntentKey.USERID, "")).setCount(count).setCommodityId(id).setMerchantId(merchantid).setSpecificationId(specificationId).setPrice(price).setCondimentsId(condimentsId)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode() == 0) {
                    selectMyCart();
                    selectByName();
                }else {
                    toast(data.getList());
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void selectToBeConfirmed() {
        orderList.clear();
        if (datacartList.size() != 0) {
            for (int i = 0; i < datacartList.size(); i++) {
                orderList.add(datacartList.get(i).getCartId() + "");
            }
        } else {
            toast("购物车还空着");
            return;
        }
        EasyHttp.post(this)
                .api(new SelectToBeConfirmedApi().setUserid(SPUtil.get(this, IntentKey.USERID, "")).setSchoolId(SPUtil.get(this, IntentKey.ADDRESSID, "")).setCartIds(CourseUtils.listToString1(orderList))).request(new HttpCallback<SelectToBeConfirmedBean>(this) {

            @Override
            public void onSucceed(SelectToBeConfirmedBean data) {
                if (data.getCode() == 0) {
                    startActivity(new Intent(BusinessSearchActivity.this, ConfirmOrderActivity.class).putExtra("orderList", data.getList()).putExtra("cartIds", CourseUtils.listToString1(orderList)));
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    private boolean useLoop( List<SelectMyCartBean.ListBean.CartsBean> dataBeanList,String id) {
        for (int i = 0; i < dataBeanList.size(); i++) {
            if (String.valueOf(dataBeanList.get(i).getCommodityId()).equals(id)) {
                return true;
            }
        }
        return false;
    }

    /**
     * // 点击加号 判断是否有规格
     *
     * @param id
     */
    private void isAttr(String id, String count, String prePrice, String price, String commodityName, String condimentsId) {
        EasyHttp.post(new ApplicationLifecycle())
                .api(new SetByCommodityIdApi().setId(id)).request(new OnHttpListener<SetByCommodityIdBean>() {

            @Override
            public void onSucceed(SetByCommodityIdBean data) {
                if (data.getCode() == 0) {
                    if (data.getList().getSpecificationCategoryNameOne()==null) {
// 没有规格 直接加入购物车
//                        if (count.equals("0")) {
//                            deleteByIds(id);
//                        } else {

                            addShopCart(id, count, "", price, condimentsId);
//                        }
                    } else {

// 有规格 有规格显示规格dialog

                    }
                    //        商家小料
                    shangjiaxiaoliao(data.getList().getSpecificationCategoryNameOne(), data.getList().getSpecificationCategoryListOne(), data.getList().getSpecificationCategoryNameTwo(), data.getList().getSpecificationCategoryListTwo(), id, commodityName, count,price,condimentsId);
                }
            }

            @Override
            public void onFail(Exception e) {


            }
        });

    }
    /**
     * 商家是否有小料
     */
    private void shangjiaxiaoliao(String name1, List<SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean> listone, String name2, List<SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean> listtwo, String id, String commodityName, String count,String price,String condimentsId) {
        EasyHttp.post(this)
                .api(new CondimentsQueryApi().setCommodityId(id)).request(new HttpCallback<CondimentsQueryBean>(this) {

            @Override
            public void onSucceed(CondimentsQueryBean data) {
                if (data.getCode() == 0) {
                    dataxiaoliaoList.clear();
                    dataxiaoliaoList.addAll(data.getList());
                    if (listone!=null||name1!=null||listtwo!=null||data.getList().size()>0) {
                        goodsAttrDialog = new GoodsAttrDialog(BusinessSearchActivity.this, name1, listone, name2, listtwo, dataxiaoliaoList, id, commodityName, count,price,"","");
                        goodsAttrDialog.show();
                        goodsAttrDialog.setOnGoodsAttrListener(new GoodsAttrDialog.OnGoodsAttrListener() {

                            @Override
                            public void onAddShoppingCart(String id, String count, String specificationId, String price, String condimentsId,String cartId, String countcart) {
                                addShopCart(id, count, specificationId, price, condimentsId);
                            }

                            @Override
                            public void dissmiss() {

                            }


                        });
                    }
                }else {
//                    if (count.equals("0")) {
//                        deleteByIds(id);
//                    } else {

                        addShopCart(id, count, "", price, condimentsId);
//                    }
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    public interface OnAddCartrListener {


        void onAddShoppingCart(String Id,String count,String prePrice,String price,String commodityName,String condimentsId);


        void onReduceShoppingCart(String Id,String count,String prePrice,String price,String commodityName,String condimentsId,String cartId);

    }

    public void setOnGoodsOrderListener(BusinessAdapter.OnAddCartrListener onAddCartrListener) {
        this.onAddCartrListener = onAddCartrListener;
    }

    @OnClick({R.id.image_back, R.id.title_bar_txt_right, R.id.tv_xiadan,R.id.rl_bottom})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.title_bar_txt_right:

                if (etSearch.getText().toString().trim().isEmpty()){
                    toast("请输入搜索商品");
                    return;
                }
                selectByName();
                break;
            case R.id.tv_xiadan:
                selectToBeConfirmed();
                break;
            case R.id.rl_bottom:
                shoppingCartDialog = new ShoppingCartDialog(BusinessSearchActivity.this, merchantid, datacartList);
                shoppingCartDialog.show();
                shoppingCartDialog.setOnGoodsOrderListener(new ShoppingCartDialog.OnGoodsOrderListener() {
                    @Override
                    public void onDismiss(String[] specification, String num, String shopPrice, String intPrice, String vipPrice, String integralPrice, String deductionIntegral) {

                    }

                    @Override
                    public void onAddShoppingCart(String id, String count, String prePrice, String price, String condimentsId, String cardId,String cartcount) {
//                        if (cartcount.equals("0")) {
//                            deleteByIds(cardId);
//                        } else {
                            addShopCart(id, count, prePrice, price, condimentsId);
//                        }
                    }

                    @Override
                    public void onSubShoppingCart() {
                        selectMyCart();
                        selectByName();
                    }

                    @Override
                    public void OrderCom(List<String> orderList) {
                        selectToBeConfirmed();
                    }


                });
                break;

        }
    }
}
